﻿using System;
using System.Collections.ObjectModel;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Configuration;

namespace SilverlightApplication1.Web
{
	/// <summary>
	/// This class just to make sample injection into WCF chain.
	/// </summary>
	public class SomeWcfBehavior
		:
		// It used to allow configuration via configuration (web.config, app.config).
		BehaviorExtensionElement,

		// One of the WCF extension approaches.
		// it3xl.ru: IEndpointBehavior vs IServiceBehavior - http://blogs.msdn.com/b/mahjayar/archive/2006/02/27/540033.aspx 
		// + https://wcfpro.wordpress.com/2011/06/03/choosing-the-right-extensibility-point/
		IServiceBehavior
	{

		#region Implementation of IServiceBehavior

		public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
		{
			// Not used.
		}

		public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
		{
			// Not used.
		}

		public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
		{
			// The next code is one of the WCF extension approaches.

			foreach (ChannelDispatcher chDisp in serviceHostBase.ChannelDispatchers)
			{
				foreach (EndpointDispatcher epDisp in chDisp.Endpoints)
				{
					epDisp.DispatchRuntime.MessageInspectors.Add(new SomeDispatchMessageInspector());
				}
			}
		}

		#endregion


		// Don't waste time here.
		#region Overrides of BehaviorExtensionElement

		// Don't waste time here.
		public override Type BehaviorType
		{
			get
			{
				return GetType();
			}
		}

		// Don't waste time here.
		protected override object CreateBehavior()
		{
			return new SomeWcfBehavior();
		}

		#endregion

	}
}